package com.cskaoyan.jdbc.dbutils;

import com.cskaoyan.jdbc.datasource.druid.DruidUtils;
import com.cskaoyan.jdbc.dbutils.bean.Account;
import com.cskaoyan.jdbc.dbutils.bean.Stu;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.*;

import javax.management.Query;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * 创建日期: 2022/05/16 11:17
 *
 * @author ciggar
 */
public class ResultSetHandlerDemo {

    static QueryRunner queryRunner;

    static {

        queryRunner = new QueryRunner(DruidUtils.getDataSource());

    }



    public static void main(String[] args) throws SQLException {

        // BeanHandler
//        testBeanHandler();
//        testBeanHandlerDemo2();


        // BeanListHandler
//        testBeanListHandler();


        // MapHandler
//        testMapHandler();

        // mapListHandler
//        testMapListHandler();

        // columnListHandler
//        testColumnListHandler();

        // ScalarHandler
        testScalarHandler();
    }


    // BeanHandlerDemo1
    public static void testBeanHandler() throws SQLException {

        Account account = queryRunner.query("select * from account where id = ?",new BeanHandler<>(Account.class),2);

        System.out.println(account);
    }

    // BeanHandlerDemo2
    // 要求使用的时候，Java对象中的成员变量名 和 表中的列名保持一致，假如不一致，就会导致不一致的成员变量封装不进去

    // 如果解决这个问题呢？
    // 可以对SQL语句起别名 | 没有别的手段了
    public static void testBeanHandlerDemo2() throws SQLException {

        Stu stu = queryRunner.query("select id,name,age,class as clazz from stu where id = ?",new BeanHandler<>(Stu.class),2);

        System.out.println(stu);
    }


    // BeanListHandler
    public static void testBeanListHandler() throws SQLException {

        List<Stu> stuList = queryRunner.query("select id,name,age,class as clazz from stu",new BeanListHandler<>(Stu.class));

        System.out.println(stuList);
    }


    // Maphandler
    public static void testMapHandler() throws SQLException {

        Map<String, Object> map = queryRunner.query("select * from stu", new MapHandler());

        System.out.println(map);


    }


    // MapListHandler
    public static void testMapListHandler() throws SQLException {

        List<Map<String, Object>> mapList = queryRunner.query("select * from  stu", new MapListHandler());


        System.out.println(mapList);
    }


    // ColumnListHandler
    public static void testColumnListHandler() throws SQLException {


        List<Object> list = queryRunner.query("select name from student", new ColumnListHandler<>());

        System.out.println(list);
    }

    // ScalarHandler
    public static void testScalarHandler() throws SQLException {


        Long count = queryRunner.query("select count(*) from student", new ScalarHandler<Long>());

        System.out.println(count);
    }




}
